package com.zhizuobiao.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;

/**
 * 下载
 * 提供资源给用户下载
 */
@Controller
public class DownloadController {

    @RequestMapping("/testdownload")
    public ResponseEntity<byte[]> testDownload() throws IOException {
        // 文件地址
        File downloadFile = new File("D:\\1_java\\RSAUtil.java");

        String filename = "测试下载.java";

        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置内容类型
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 解决中文乱码问题
        filename = new String(filename.getBytes("utf-8"), "iso-8859-1");

        // 设置文件名
        httpHeaders.setContentDispositionFormData("attachment", filename);

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(
                FileUtils.readFileToByteArray(downloadFile),
                httpHeaders,
                HttpStatus.CREATED
        );

        return responseEntity;
    }
}
